package com.hnas.ecard.dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import com.hnas.core.dao.BaseDaoImpl;
import com.hnas.core.util.DateUtil;
import com.hnas.core.util.StringUtil;
import com.hnas.ecard.dao.CommoditDao;
import com.hnas.ecard.orm.Commodit;
import com.hnas.ecard.service.dto.DTOCommodit;
import com.hnas.ecard.service.search.DTOCommoditSearch;

@Component("commoditDao")
public class CommoditDaoImpl extends BaseDaoImpl<Commodit> implements CommoditDao{

	public CommoditDaoImpl() {
		super(Commodit.class);
	}

	@Override
	public Commodit saveOrUpdate(DTOCommodit vo) throws Exception {
		Commodit temp = null;
		if(null != vo){
			if(StringUtil.isNotEmpty(vo.getId())){
				temp = this.find(vo.getId());
			}
			if(null == temp){
				temp = new Commodit();
				BeanUtils.copyProperties(vo, temp);
				temp.setCreateTime(DateUtil.dateTimeToString(new Date()));
				temp.setUpdateTime(DateUtil.dateTimeToString(new Date()));
				temp.setIsDeleted(false);
				this.persist(temp);
			}else{
				BeanUtils.copyProperties(vo, temp,new String[]{"id", "createTime"});
				temp.setUpdateTime(DateUtil.dateTimeToString(new Date()));
				this.merge(temp);
			}
		}
		return temp;
	}

	@Override
	public List<Commodit> pageByMrchId(DTOCommoditSearch criteria) {
		String sql = "from Commodit t where t.mrchId = ?1 order by t.price asc";
		Query query = this.entityManager.createQuery(sql);
		query.setParameter(1, criteria.getMrchId());
		query.setFirstResult((criteria.getPageNo()-1)*criteria.getPageSize());
		query.setMaxResults(criteria.getPageSize());
		List<Commodit> resultList = query.getResultList();
		return resultList;
	}

	@Override
	public boolean deleteById(String id) {
		if(StringUtil.isEmpty(id)) return false;
		String sql = "delete from tbl_commodit where id = ?1";
		Query query = this.entityManager.createNativeQuery(sql);
		query.setParameter(1, id);
		return query.executeUpdate() == 1;
	}

}
